/* eslint-disable no-undef */
import Request from "@/api/baseRequest.js";
// import wx from 'weixin-js-sdk'

export const mixin_Pay = {
    data() {
        return {
            urlParam: null,
            money: 0.01,
            weChatParameter: null
        }
    },
    methods: {
        info(title) {
            this.$message(title);
        },
        success(title) {
            this.$message({
                message: title,
                type: 'success'
            });
        },
        warning(title) {
            this.$message.warning(title);
            this.$message({
                message: title,
                type: 'warning'
            });
        },
        error(title) {
            this.$message.error(title);
        },
        back() {
            if (window.history.length <= 1) {
                this.$router.push({ path: "/" });
                return false;
            } else {
                this.$router.go(-1);
            }
            //上面都没执行就说明卡在当前页不是最后一条， histroy记录数量大于1，又没有回退记录，只能返回首页，
            //如果上面都执行了 页面都跳走了，这个也就不用管了
            setTimeout(() => {
                this.$router.push({ path: "/" });
            }, 500);
        },
        // 截取code
        GetParam(url, code) {
            url = url + "";
            let regstr = "/(\\?|\\&)" + code + "=([^\\&]+)/";
            let reg = eval(regstr);
            let result = url.match(reg);
            if (result && result[2]) {
                return result[2];
            }
        },
        /* getShareInfo(tit, fxUrl) { //如果分享的内容会根据情况变化，那么这里可以传入分享标题及url
            let _this = this;
            var data = { //请求参数
                url: this.jmUrl,
                token: this.token,
                code: this.code
            }
            // eslint-disable-next-line no-undef
            //这里我写了一个公用的接口请求js，这里正常axios请求就可以，只要拿到数据都可以
            Request.getShare(data).then(res => {
                localStorage.setItem("jsapi_ticket", res.jsapi_ticket);
                //拿到后端给的这些数据
                let timestamp = res.timestamp;
                let nonceStr = res.noncestr;
                let signature = res.signature;
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: this.appid, // 必填，公众号的唯一标识，填自己的！
                    timestamp: timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
                    nonceStr: nonceStr, // 必填，生成签名的随机串
                    signature: signature, // 必填，签名，见附录1
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage'
                    ]
                })
                wx.ready(function() {
                    //分享到朋友圈
                    wx.onMenuShareTimeline({
                        title: tit, // 分享时的标题
                        link: fxUrl, // 分享时的链接
                        imgUrl: _this.pic, // 分享时的图标
                        success: function() {
                            this.$Alert({ title: "分享", message: '成功分享至朋友圈' });
                        },
                        cancel: function() {
                            this.$Alert({ title: "分享", message: '取消分享' });
                        }
                    });
                    //分享给朋友
                    wx.onMenuShareAppMessage({
                        title: tit,
                        // desc: '这件商品终于优惠了，每件只需' + pri_fx + '元',
                        link: fxUrl,
                        imgUrl: _this.pic,
                        type: '',
                        dataUrl: '',
                        success: function() {
                            console.log("分享成功");
                            this.$Alert({ title: "分享", message: '成功分享给朋友' });
                        },
                        cancel: function() {
                            this.$Alert({ title: "分享", message: '取消分享' });
                        }
                    });
                })
            })
        }, */
        async handelPay(orderNo) {
            let params = {
                activityId: this.GetParam(window.location.href, "id") || sessionStorage['id'],
                userId: this.GetParam(window.location.href, "userId") || sessionStorage['userId'],
                orderNo,
            };
            //根据后端所需传参数
            this.isDisabledSubmitBtn = true; //防止用户点击多次
            let result = await Request.activityPay(params);
            if ([200, "200", "OK", 0].includes(result.code)) {
                this.weChatParameter = result.payResult;
                this.$set(this.weChatParameter, 'package', result.payResult.packageValue)
                delete this.weChatParameter.packageValue;
                this.weixinPay(this.weChatParameter);
            }
        },
        //解决微信内置对象报错
        weixinPay(params) {
            var that = this;
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener(
                        "WeixinJSBridgeReady",
                        that.onBridgeReady(params),
                        false
                    );
                } else if (document.attachEvent) {
                    document.attachEvent(
                        "WeixinJSBridgeReady",
                        that.onBridgeReady(params)
                    );
                    document.attachEvent(
                        "onWeixinJSBridgeReady",
                        that.onBridgeReady(params)
                    );
                }
            } else {
                that.onBridgeReady(params);
            }
        },
        //微信内置浏览器类，weChatParameter对象中的参数是3.步骤代码中从后端获取的数据
        onBridgeReady(params) {
            var that = this;
            WeixinJSBridge.invoke(
                "getBrandWCPayRequest", {
                    ...params,
                    jsApiList: ["chooseWXPay"],
                },
                function(res) {
                    this.$Alert({ title: "支付信息", message: res, duration: 1000*200 });
                    // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        //支付成功后的操作
                        this.$state.commit('payStatus', true);
                        this.$Alert({ title: "支付", message: '支付成功' });
                        that.isDisabledSubmitBtn = true;
                        location.reload();
                        this.$router.go(0);
                    } else if (
                        res.err_msg == "get_brand_wcpay_request:cancel"
                    ) {
                        //取消支付的操作
                        this.$Alert({ title: "活动报名", message: '已取消支付' });
                        that.isDisabledSubmitBtn = false; //按钮恢复高亮
                    } else {
                        //支付失败的操作
                        this.$Alert({ title: "支付", message: '支付失败' });
                        that.isDisabledSubmitBtn = false; //按钮恢复高亮
                    }
                },
            );
        }
    },
    watch: {
        '$route.path': function(o) {
            this.urlParam = o;
        }
    },
    destroyed() {},
}
